package gitobject;
import fileoperation.FileReader;
import repository.Repository;
import zlib.ZLibUtils;

import java.io.*;

public class GitObject {

    protected String fmt;                  //type of object
    protected String key;                  //key of object
    protected String mode;                 //mode of object
    protected static String path = Repository.getGitDir() + File.separator + "objects";          //absolute path of objects
    protected String value;                //value of object

    public String getFmt(){
        return fmt;
    }
    public String getKey() { return key; }
    public String getMode(){
        return mode;
    }
    public String getPath() {
        return path;
    }
    public String getValue(){
        return value;
    }


    public GitObject(){}
    /**
     * Get the value(content) of file
     * @param file
     * @return String
     * @throws IOException
     */
    // 通过IO流，从某个文件中读取文件的内容，将内容转为字符串返回出去
    public static String getValue(File file) throws IOException {
        try( FileInputStream input = new FileInputStream(file)){
            byte[] byt = new byte[input.available()];
            input.read(byt);
            String fileContent = new String(byt);
            return fileContent;
        }
    }
    /**
     * Todo: Serialize the object to the local repository.
     * @throws Exception
     */
    // 序列化到本地
    public void writeObject() throws Exception{
        // 序列化git对象的内容，写入key值所对应的文件
        FileReader.writeValue(path + File.separator + key.substring(0,2)+File.separator+key.substring(2),value);
    }

    /**
     * Todo: Serialize the object and compress with zlib.
     * @throws Exception
     */
    // 序列化git对象，将文件内容进行压缩，并写入objects目录下对应的文件内
    public void compressWrite() throws Exception{
        // 将git对象的内容进行压缩存到bytes里
        byte[] bytes = ZLibUtils.compress(value.getBytes());
        // 在当前objects的文件夹下的，按照key值锁定目标文件，创建输出流
        FileOutputStream output = new FileOutputStream(this.getPath() + File.separator + key.substring(0,2)+File.separator+ key.substring(2));
        // 在该目标文件内，写入压缩后的文件内容
        output.write(bytes);
        output.close();
    }
}
